package com.huajin.gateway.netcard.controller;

import com.huajin.gateway.netcard.domain.NetCard;
import com.huajin.gateway.netcard.service.NetCardService;
import com.huajin.gateway.util.SystemCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.net.SocketException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/netcard")
public class NetCardController {

    @Autowired
    private NetCardService netCardService;

    @GetMapping("/list")
    public List<NetCard> listAllNetCards() throws SocketException {
        return netCardService.listNetCard();
    }

    @GetMapping("/getcardbyname")
    public NetCard getCardByName(@RequestParam String name) throws SocketException {
        return netCardService.listNetCardByName(name);
    }

    @PostMapping("/modify")
    public boolean modifyNetCardByName(@RequestBody NetCard netCard) {

        //must to del the older ip then add the new;
        //TODO need to consider the mask
        //static
        NetCard older = netCardService.listNetCardByName(netCard.getName());
        if (older.getIp() != null) {
            netCardService.delIpbyName(older.getIp(), older.getName());
        }
        if (netCard.getDynamic()) {
            netCardService.setDynamicOn(netCard.getName());
            //set dynamic stop
        } else {
            netCardService.setDynamicOff(netCard.getName());
            netCardService.addIpbyName(netCard.getIp(), netCard.getName());
        }
        if (netCard.getMtu() != null) {
            netCardService.setMtubyName(netCard.getName(), netCard.getMtu());
        }
        return true;
    }

    @PostMapping("/changestatusbyname")
    public boolean changeStatusByName(@RequestBody Map<String, String> parameter) {
        String name = parameter.get("name");
        String status = parameter.get("status");
        if (name != null) {
            if (status.equals("up")) {
                netCardService.changeStatusOnbyName(name);
            } else if (status.equals("down")) {
                netCardService.changeStatusOffbyName(name);
            }
            return true;
        } else
            return false;
    }

    @PostMapping("/batchsetonbyname")
    public boolean batchSetOnByName(@RequestBody List<String> netCardsName) {
        for (String s : netCardsName) {
            netCardService.changeStatusOnbyName(s);
        }
        return true;
    }

    @PostMapping("/batchsetoffbyname")
    public boolean batchSetOffByName(@RequestBody List<String> netCardsName) {
        for (String s : netCardsName) {
            netCardService.changeStatusOffbyName(s);
        }
        return true;
    }
}
